import { type NextRequest, NextResponse } from "next/server"
import { createServerSupabaseClient } from "@/lib/supabase-server"

export async function POST(request: NextRequest) {
  try {
    const { action, data } = await request.json()
    const supabase = createServerSupabaseClient()

    console.log(`API Route - Handling action: ${action}`)

    switch (action) {
      case "checkConnection":
        return NextResponse.json({ connected: true }, { status: 200 })

      case "getActivePolls":
        const { data: polls, error } = await supabase
          .from("polls")
          .select(`
            *,
            poll_options(*)
          `)
          .eq("active", true)
          .order("created_at", { ascending: false })

        if (error) throw error
        return NextResponse.json({ polls }, { status: 200 })

      case "getAllPolls":
        const { data: allPolls, error: allPollsError } = await supabase
          .from("polls")
          .select(`
            *,
            poll_options(*)
          `)
          .order("created_at", { ascending: false })

        if (allPollsError) throw allPollsError
        return NextResponse.json({ polls: allPolls }, { status: 200 })

      case "getPoll":
        const { data: poll, error: pollError } = await supabase
          .from("polls")
          .select(`
            *,
            poll_options(*),
            comments(*)
          `)
          .eq("id", data.id)
          .single()

        if (pollError) throw pollError
        return NextResponse.json({ poll }, { status: 200 })

      case "createPoll":
        return handleCreatePoll(supabase, data.title, data.description, data.options)

      case "vote":
        return handleVote(supabase, data.pollId, data.optionId, data.voterId)

      case "addComment":
        return handleAddComment(supabase, data.pollId, data.text)

      case "updatePollStatus":
        return handleUpdatePollStatus(supabase, data.id, data.active)

      case "deletePoll":
        return handleDeletePoll(supabase, data.id)

      default:
        return NextResponse.json({ error: "Invalid action" }, { status: 400 })
    }
  } catch (error: any) {
    console.error("API error:", error)
    return NextResponse.json({ error: error.message || "Server error" }, { status: 500 })
  }
}

// 创建新投票
async function handleCreatePoll(supabase: any, title: string, description: string, options: string[]) {
  try {
    // 开始事务
    const { data: poll, error: pollError } = await supabase
      .from("polls")
      .insert([{ title, description, active: true }])
      .select()
      .single()

    if (pollError) throw pollError

    // 添加选项
    const optionsToInsert = options.map((text) => ({
      poll_id: poll.id,
      text,
      votes: 0,
    }))

    const { error: optionsError } = await supabase.from("poll_options").insert(optionsToInsert)

    if (optionsError) throw optionsError

    return NextResponse.json({ poll }, { status: 200 })
  } catch (error: any) {
    console.error("Error in createPoll:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

// 投票
async function handleVote(supabase: any, pollId: string, optionId: string, voterId: string) {
  try {
    // 检查是否已投票
    const { data: existingVote, error: checkError } = await supabase
      .from("vote_records")
      .select()
      .eq("poll_id", pollId)
      .eq("voter_id", voterId)
      .maybeSingle()

    if (checkError) throw checkError

    if (existingVote) {
      return NextResponse.json({ error: "您已经参与过此投票" }, { status: 400 })
    }

    // 记录投票
    const { error: recordError } = await supabase.from("vote_records").insert([{ poll_id: pollId, voter_id: voterId }])

    if (recordError) throw recordError

    // 增加票数
    const { error: updateError } = await supabase.rpc("increment_votes", { option_id: optionId })

    if (updateError) throw updateError

    return NextResponse.json({ success: true }, { status: 200 })
  } catch (error: any) {
    console.error("Error in vote:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

// 添加评论
async function handleAddComment(supabase: any, pollId: string, text: string) {
  try {
    const { data: comment, error } = await supabase
      .from("comments")
      .insert([{ poll_id: pollId, text }])
      .select()
      .single()

    if (error) throw error

    return NextResponse.json({ comment }, { status: 200 })
  } catch (error: any) {
    console.error("Error in addComment:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

// 更新投票状态
async function handleUpdatePollStatus(supabase: any, id: string, active: boolean) {
  try {
    const { error } = await supabase.from("polls").update({ active }).eq("id", id)

    if (error) throw error

    return NextResponse.json({ success: true }, { status: 200 })
  } catch (error: any) {
    console.error("Error in updatePollStatus:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

// 删除投票
async function handleDeletePoll(supabase: any, id: string) {
  try {
    const { error } = await supabase.from("polls").delete().eq("id", id)

    if (error) throw error

    return NextResponse.json({ success: true }, { status: 200 })
  } catch (error: any) {
    console.error("Error in deletePoll:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}
